package org.lmind.example.common.web.spring;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.lmind.example.common.web.ApplicationContext;
import org.lmind.example.common.web.SessionContext;
import org.lmind.example.common.web.SessionContextManager;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;

public class GeneralModelAndViewResolver implements ModelAndViewResolver {
	
	private ApplicationContext applicationContext;
	
	private SessionContextManager sessionContextManager;

	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	public void setSessionContextManager(SessionContextManager sessionContextManager) {
		this.sessionContextManager = sessionContextManager;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public ModelAndView resolveModelAndView(Method handlerMethod,
			Class handlerType, Object returnValue,
			ExtendedModelMap implicitModel, NativeWebRequest webRequest) {
		
		SessionContext sessionContext = sessionContextManager.getCurrentThread();
		ExtraViewModel context = new ExtraViewModel(applicationContext, 
				sessionContext, webRequest.getNativeRequest(HttpServletRequest.class));
		
		if (!(returnValue instanceof PageView)) {
			return UNRESOLVED;
		}
		PageView view = (PageView)returnValue;
		
		ModelAndView mv = new ModelAndView(view.getName());
		mv.addObject("model", view.getModel());
		mv.addObject("context", context);
		return mv;
	}

}
